
$(function () {
    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            Seach.do();
        }
    });
    setInterval(function () {
        Seach.loadTags();
    }, 1000*30) //半分钟执行一下
    Seach.init();
});
var url;
var record;
var tags;
var tagcolors = ["label-primary", "label-success", "label-info", "label-warning", "label-danger"]
var Seach = {
    init: function () {
        $("#btn-search").on("click", function () {
            Seach.do();
        });
        Seach.loadChoose();
        Seach.changeChoose();
        Seach.loadRecord();
        Seach.loadTags();
        Seach.openTagUrl();
        Seach.saveNewTag();
        Seach.removeTag();
        Seach.saveTagJson();
        Seach.importTagJson();
    },
    loadChoose: function () {
        let title = localStorage.getItem('CHOOSE_TITLE');
        title = !CheckIsNullOrEmpty(title) ? $("#ul-menu li").first().find("a").text() : title;
        url = localStorage.getItem('CHOOSE_URL');
        url = !CheckIsNullOrEmpty(url) ? $("#ul-menu li").first().find("a").data("url") : url;
        $("#btn-choose").text(title);
    },
    changeChoose: function () {
        $("#ul-menu li").on("click", function () {
            title = $(this).find("a").text();
            url = $(this).find("a").data("url");
            localStorage.setItem('CHOOSE_URL', url);
            localStorage.setItem('CHOOSE_TITLE', title);
            $("#btn-choose").text(title);
        })
    },
    loadRecord: function () {
        let search = localStorage.getItem('SEARCH');
        record = !CheckIsNullOrEmpty(search) ? { data: [] } : JSON.parse(search);
        let arr = record.data;
        url = !CheckIsNullOrEmpty(url) || url === '' ? "https://www.baidu.com/s?wd=" : url;
        if (arr.length > 0) {
            let innerHtml = '<ul class="dropdown-menu" role="menu" aria-labelledby="key">';
            for (i = 0; i < arr.length; i++) {
                innerHtml += '<li role="presentation"><a role="menuitem" tabindex="-1" href="' + url + Seach.EnUrl(arr[i]) + '" target="_blank">' + arr[i] + '</a></li>'
            }
            innerHtml += '</ul>';
            $("#dropdown-menu").append(innerHtml);
        }
    },
    do: function () {
        url = !CheckIsNullOrEmpty(url) || url === '' ? "https://www.baidu.com/s?wd=" : url;
        let key = $("#key").val();
        console.log(key)
        if ($.trim(key) === "") {
            openUrl(url.substr(0, url.lastIndexOf("/")));
        } else {
            let arr = record.data;
            if (arr.length >= 10) {
                arr = arr.slice(0, 9);
            }
            let newArr = [key].concat(arr);
            record.data = newArr;
            let search = JSON.stringify(record);
            localStorage.setItem('SEARCH', search);
            openUrl(url + Seach.EnUrl(key));
        }
    },
    EnUrl: function (key) {
        key = key.replace(/\%/g, "%25");
        key = key.replace(/\&/g, "%26");
        key = key.replace(/\+/g, "%2B");
        key = key.replace(/\//g, "%2F");
        key = key.replace(/\?/g, "%3F");
        key = key.replace(/\#/g, "%23");
        key = key.replace(/\=/g, "%3D");
        key = key.replace(/\ /g, "%20");
        return key;
    },
    loadTags: function () {
        let t = localStorage.getItem('TAGS');
        tags = !CheckIsNullOrEmpty(t) ? { data: [] } : JSON.parse(t);
        let arr = tags.data;
        $(".tagList").empty();
        if (arr.length > 0) {
            let innerHtml = "";
            for (i = 0; i < arr.length; i++) {
                innerHtml += '<div class="label ' + tagcolors[randomNum()] + '" title="' + arr[i].title + '"><strong data-url="' + arr[i].url + '" tag>' + arr[i].title + '</strong><a href="#" data-title="' + arr[i].title + '" tagdelete> &times;</a></div>';
            }
            $(".tagList").append(innerHtml);
        }
    },
    openTagUrl: function () {
        $("body").delegate("[tag]", "click", function () {
            let url = $(this).data("url");
            openUrl(url);
        });
    },
    saveNewTag: function () {
        $("body").delegate("#btn-saveNewTag", "click", function () {
            $("#tag-title").removeClass("error");
            $("#tag-url").removeClass("error");
            let tagTitle = $("#tag-title").val();
            let tagUrl = $("#tag-url").val();
            if ($.trim(tagTitle) === "") {
                $("#tag-title").addClass("error");
                return;
            }
            if ($.trim(tagUrl) === "") {
                $("#tag-url").addClass("error");
                return;
            }
            if ($.trim(tagTitle) !== "" && $.trim(tagUrl) !== "") {
                let arr = tags.data;
                arr.push({ "title": tagTitle, "url": tagUrl });
                tags.data = arr;
                localStorage.setItem("TAGS", JSON.stringify(tags));
                $("#tag-title").val("");
                $("#tag-url").val("");
                Seach.openTagUrl();
                Seach.removeTag();
                Seach.loadTags();
                $('#addNewTag').modal('hide');
            }
        });
    },
    removeTag: function () {
        $("body").delegate("[tagdelete]", "click", function () {
            let title = $(this).data("title");
            let arr = tags.data;
            if (arr.length > 0) {
                let arrNew = [];
                for (i = 0; i < arr.length; i++) {
                    if (arr[i].title !== title) {
                        arrNew.push(arr[i]);
                    }
                }
                tags.data = arrNew;
                localStorage.setItem("TAGS", JSON.stringify(tags));
            }
            Seach.loadTags();
        })
    },
    saveTagJson: function () {
        $("#btn-saveTagJson").on("click", function () {
            var blob = new Blob([JSON.stringify(tags)], { type: "text/plain;charset=utf-8" });
            saveAs(blob, "blackvonTags.json");
        });
    },
    importTagJson: function () {
        $("#files").on("change", function () {
            var selectedFile = document.getElementById("files").files[0];//获取读取的File对象
            var type = selectedFile.type;
            if (type !== 'application/json') {
                alert("请选择json文件！");
                return;
            }
            var reader = new FileReader();//这里是核心！！！读取操作就是由它完成的。
            reader.readAsText(selectedFile);//读取文件的内容
            reader.onload = function () {
                let json = JSON.parse(this.result);
                localStorage.setItem("TAGS", JSON.stringify(json));
                alert("还原成功！");
                Seach.loadTags();
            };
        });
        $("#btn-importTagJson").on("click", function () {
            $("#files").click();
        });
    }
}
//判断数据是否为Null或者undefined或者为空字符串
function CheckIsNullOrEmpty(value) {
    //正则表达式用于判斷字符串是否全部由空格或换行符组成
    let reg = /^\s*$/
    //返回值为true表示不是空字符串
    return (value != null && value != undefined && !reg.test(value))
}
//0-4随机数
function randomNum() {
    var x = 4;
    var y = 0;
    var rand = parseInt(Math.random() * (x - y + 1) + y);
    return rand;
}
//打开新窗口
function openUrl(url){
    var a = $('<a href="'+ url +'" target="_blank">链接</a>');  //生成一个临时链接对象
    var d = a.get(0);
    if(document.createEvent){
        var e = document.createEvent('MouseEvents');
        e.initEvent( 'click', true, true );  //模拟点击操作
        d.dispatchEvent(e);
        a.remove();   // 点击后移除该对象
    }
    else if(document.all){
        d.click();
    }
}